package com.streamkar.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ClassName FileUtil
 * @Description
 * @Author tyfrost
 * @Date 2018/11/19 4:53 PM
 * @Version 1.0
 */
@Component
public class FileUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileUtil.class);

    public String saveImg(MultipartFile multipartFile, Integer userId, String path, String accessPath) throws Exception {
        path = path + File.separator + userId;
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }

        FileInputStream fileInputStream = (FileInputStream) multipartFile.getInputStream();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String fileName = sdf.format(new Date());
        String saveFilePath = path + File.separator + fileName + ".png";
        String accessFilePath = accessPath + File.separator + userId + File.separator + fileName + ".png";

        LOGGER.info("save file,the file path:{}", saveFilePath);
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(saveFilePath));
        byte[] bytes = new byte[1024];
        int len;
        while ((len = fileInputStream.read(bytes)) != -1) {
            bufferedOutputStream.write(bytes, 0, len);
        }
        bufferedOutputStream.flush();
        bufferedOutputStream.close();
        return accessFilePath;
    }
}
